#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : Chestnut
# @time    : 2025/7/9 09:24
# @function: 数据裁剪
# @version : V1

import tkinter
import tkinter.filedialog
import datetime
import re
import os
import openpyxl
from main import PostProcesser


class DataScissor(PostProcesser):
    def __init__(self):
        super().__init__()
        self.file = None
        self.inner_title_str.set("Data scissor")
        self.str_source_dir = tkinter.StringVar()  # 数据文件夹
        self.str_target_dir = tkinter.StringVar()  # 目标文件夹
        self.str_source_file = tkinter.StringVar()  # 数据文件名
        self.str_oprate = tkinter.StringVar()  # 工况点
        self.str_posite = tkinter.StringVar()  # 测点
        self.str_apower = tkinter.StringVar()  # 有功
        self.str_flow = tkinter.StringVar()  # 流量
        self.str_date = tkinter.StringVar()  # 日期
        self.str_hour = tkinter.StringVar()  # 时
        self.str_minute = tkinter.StringVar()  # 分
        self.str_second = tkinter.StringVar()  # 秒
        self.str_lines = tkinter.StringVar()  # 行数
        self.str_expres = tkinter.StringVar()  # 自由表达式

    def single_file_execute(self):
        with open(self.str_source_file.get(), "r", encoding="utf-8") as o_f:
            self.file = o_f.read()
            self.text_plot.insert(tkinter.END, "开始读取" + o_f.name)
            self.text_plot.insert(tkinter.END, "\n")
            self.text_plot.see(tkinter.END)
            if self.str_date.get() != "" and self.str_hour.get() == "" and self.str_minute.get() == "" and self.str_second.get() == "":
                """自由模式：直接在日期栏写入正则表达式或者想要找到的行（一定是以#作为行首）"""
                self.text_plot.insert(tkinter.END, "正在以自由模式匹配……\n")
                matching = re.search(self.str_date.get() + f"(#.*\n){{{int(self.str_lines.get())}}}", self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_plot.delete("1.0", tkinter.END)
                    self.text_plot.insert(tkinter.END, self.result)
                    self.text_plot.update()
                else:
                    self.text_plot.insert(tkinter.END, "未匹配到任何数据")
            elif self.str_date.get() == "" and self.str_hour.get() != "" and self.str_minute.get() != "" and self.str_second.get() != "":
                """标准模式：在时间栏填入时分秒（24小时制）即可得到想要的行"""
                self.text_plot.insert(tkinter.END, "正在以标准模式匹配……\n")
                matching = re.search(
                    "(#.*)" + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{self.str_lines.get()}}}",
                    self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_plot.delete("1.0", tkinter.END)
                    self.text_plot.insert(tkinter.END, self.result)
                    self.text_plot.update()
                else:
                    self.text_plot.insert(tkinter.END, "未匹配到任何数据")
            elif self.str_date.get() != "" and self.str_hour.get() != "" and self.str_minute.get() != "" and self.str_second.get() != "":
                """扩展模式：在日期栏填入日期(yyyy-mm-dd)，并在时间栏填入时分秒（24小时制）即可得到想要的行"""
                self.text_plot.insert(tkinter.END, "正在以扩展模式匹配……\n")
                matching = re.search(
                    "(#.*)" + self.str_date.get() + " " + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                    self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_plot.delete("1.0", tkinter.END)
                    self.text_plot.insert(tkinter.END, self.result)
                    self.text_plot.update()
                else:
                    self.text_plot.insert(tkinter.END, "未匹配到任何数据,开始尝试第二次匹配\n")
                    date_str_list = self.str_date.get().split("-")
                    matching = re.search(
                        "(#.*)" + date_str_list[
                            2] + " Jun 2025" + "(.*)" + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                        self.file)
                    if matching != None:
                        self.result = matching.group()
                        self.text_plot.delete("1.0", tkinter.END)
                        self.text_plot.insert(tkinter.END, self.result)
                        self.text_plot.update()
                    else:
                        self.text_plot.insert(tkinter.END, "未匹配到任何数据,开始尝试第三次匹配\n")
                        matching = re.search(
                            "(#.*)" + self.str_date.get().replace("-0",
                                                                  '-') + " " + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                            self.file)
                        if matching is not None:
                            self.result = matching.group()
                            self.text_plot.delete("1.0", tkinter.END)
                            self.text_plot.insert(tkinter.END, self.result)
                            self.text_plot.update()
                        else:
                            self.text_plot.insert(tkinter.END, "未匹配到任何数据,匹配结束\n")
            self.text_plot.see(tkinter.END)

    def mutiple_files_execute(self):
        pass

    def set_main_frm(self):
        tkinter.Label(self.main_frm, text="文件裁剪").grid(row=0, column=0, sticky=tkinter.NSEW)
        row1 = tkinter.Frame(self.main_frm)
        comm_width = 30
        tkinter.Label(row1, text="工况").grid(row=0, column=0, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_oprate, width=comm_width).grid(row=1, column=0, sticky=tkinter.EW)
        tkinter.Label(row1, text="测点").grid(row=0, column=1, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_posite, width=comm_width).grid(row=1, column=1, sticky=tkinter.EW)
        tkinter.Label(row1, text="有功").grid(row=0, column=2, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_apower, width=comm_width).grid(row=1, column=2, sticky=tkinter.EW)
        tkinter.Label(row1, text="流量").grid(row=0, column=3, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_flow, width=comm_width).grid(row=1, column=3, sticky=tkinter.EW)
        tkinter.Label(row1, text="日期").grid(row=2, column=0, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_date, width=comm_width).grid(row=3, column=0, sticky=tkinter.EW)
        tkinter.Label(row1, text="时").grid(row=2, column=1, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_hour, width=comm_width).grid(row=3, column=1, sticky=tkinter.EW)
        tkinter.Label(row1, text="分").grid(row=2, column=2, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_minute, width=comm_width).grid(row=3, column=2, sticky=tkinter.EW)
        tkinter.Label(row1, text="秒").grid(row=2, column=3, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_second, width=comm_width).grid(row=3, column=3, sticky=tkinter.EW)
        tkinter.Label(row1, text="自由模式").grid(row=4, column=0, columnspan=3, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_expres, width=comm_width).grid(row=5, column=0, columnspan=3,
                                                                                 sticky=tkinter.EW)
        tkinter.Label(row1, text="行数").grid(row=4, column=3, sticky=tkinter.EW)
        tkinter.Entry(row1, textvariable=self.str_lines, width=comm_width).grid(row=5, column=3, sticky=tkinter.EW)
        tkinter.Label(row1, text="执行文件:", font="5px").grid(row=5, column=0, sticky=tkinter.EW)
        tkinter.Label(row1, textvariable=self.str_source_file, borderwidth=1, relief="sunken").grid(row=5, column=1,
                                                                                                    columnspan=3,
                                                                                                    sticky=tkinter.EW)
        tkinter.Label(row1, text="保存路径:", font="5px").grid(row=6, column=0, sticky=tkinter.EW)
        tkinter.Label(row1, textvariable=self.str_target_dir, borderwidth=1, relief="sunken").grid(row=6, column=1,
                                                                                                    columnspan=3,
                                                                                                    sticky=tkinter.EW)
        row1.grid(row=1, column=0, sticky=tkinter.EW)

    def set_plot_frm(self):
        self.text_plot = tkinter.Text(self.main_window,height=5)
        self.text_plot.grid(column=1,row=2,sticky=tkinter.NSEW)

    def set_menubar(self):
        self.mainmenu.add_command(label="打开原始数据", command=self.ask_origin_dir)
        self.mainmenu.add_command(label="打开保存位置", command=self.ask_directory)
        self.mainmenu.add_command(label="单文件裁切", command=self.single_file_execute)
        self.mainmenu.add_command(label="全部裁切", command=self.mutiple_files_execute)
        self.mainmenu.add_command(label="退出", command=quit)

    def ask_origin_dir(self):
        super().ask_directory()
        self.str_source_dir.set(self.dir_path)  # 标准化赋值
        for file_name in os.listdir(self.dir_path):
            self.lb.insert(tkinter.END, file_name)  # 左侧栏展示

    def ask_save_dir(self):
        super().ask_directory()



myapp = DataScissor()
myapp.start()
